package com.yhthu.texthandler;

import com.yhthu.bean.Record;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RecordHandler extends BaseHandler<Record> {

    @Override
    public List<Record> getValidObjectFromTextContent(String content) {
        List<Record> validRecords = new ArrayList<>();
        // 由一个完整信息记录组成的集合
        String[] records = super.executeSingleSplitStrategy(content);
        getValidObjectFromSingleRecord(validRecords, records);
        return validRecords;
    }

    public void getValidObjectFromSingleRecord(List<Record> recordList, String[] records) {
        for (String recordStr : records) {
            // 由单行信息组成的记录集合
            String[] lineRecords = super.executeLineSplitStrategy(recordStr);
            getValidObjectFromLineRcord(recordList, lineRecords);
        }
    }

    public void getValidObjectFromLineRcord(List<Record> recordList, String[] lineRecords) {
        Map<String, String> keyValueMap = getBlankRecordMap();
        String previousKey = null;
        for (String lineRecord : lineRecords) {
            lineRecord = lineRecord.replaceFirst("\\n", "").trim();
            String firstWord = super.executeWordSplitStrategy(lineRecord)[0];
            if (keyValueMap.keySet().contains(firstWord.toLowerCase())) {
                keyValueMap.put(firstWord.toLowerCase(), lineRecord.substring(firstWord.length()).trim());
                previousKey = firstWord;
            } else {
                String previousValue = keyValueMap.get(previousKey);
                if (previousValue != null) {
                    keyValueMap.put(previousKey, previousValue.concat(" " + lineRecord.trim()));
                }
            }
        }
        Record record = Record.getRecordByAttributesMap(keyValueMap);
        if (record.isValidRecord()) {
            recordList.add(record);
        }
    }

    private Map<String, String> getBlankRecordMap() {
        Map<String, String> keyValueMap = new HashMap<>();
        keyValueMap.put("name", "");
        keyValueMap.put("birthday", "");
        keyValueMap.put("phone", "");
        keyValueMap.put("recipient", "");
        keyValueMap.put("donation", "");
        keyValueMap.put("address", "");
        keyValueMap.put("postcode", "");
        return keyValueMap;
    }
}
